# -*- coding: utf-8 -*-
from shlex import split
from subprocess import Popen, PIPE
from re import sub
import time
# import chardet

file_path = "./WR-IMP-MIB.txt"
# chardet.detect(msg)["encoding"]


def snmpset(community: str = "public", host: str = None, OIDname: str = None, mask: str = None, set_type: str = None, set_value: float = None):
    command = "snmpset -v 2c -c {} -m {} {} {} {} {}".format(
        community, file_path, host, OIDname, set_type, set_value)
    #print(command)
    try:
        proc = Popen(split(
            command), shell=False, stdout=PIPE, stderr=PIPE)
        proc.wait()
        if proc.poll() == 0:
            msg = proc.stdout.read().decode("gb2312")
            msg = msg.split("{}".format(mask))
            msg = sub("[^\d]".format(mask), "", msg[1])
        else:
            msg = proc.stderr.read().decode("gb2312")
    except:
        msg = "\""+command + "\" is Error"
    return msg


def snmpget(community: str = "public", host: str = None, OIDname: str = "impWavePatternTable1"):
    # command = "echo {} {} {}".format(
    #     community, mask, set_value)
    # proc = Popen(split(
    #     command), shell=True, stdout=PIPE, stderr=PIPE)
    command = "snmpwalk -v 2c -c {} -m {} {} {}".format(
        community, file_path, host, OIDname)
    # print(command)
    try:
        proc = Popen(split(
            command), shell=False, stdout=PIPE, stderr=PIPE)
        proc.wait()
        if proc.poll() == 0:
            msg = proc.stdout.read().decode("gb2312")
            # msg = msg.split("{}".format(mask))
            # msg = sub("[^\d]".format(mask), "", msg)
        else:
            msg = proc.stderr.read().decode("gb2312")
    except:
        msg = "\""+command + "\" is Error"
    return msg


if __name__ == "__main__":
    # 测试
    a = snmpget()
    print(a)
